package com.lizk.sort;

import java.util.Random;

/**
 * @author lizhikui
 * @date 2020/2/6 14:07
 */
public class SortUtils {
    /**
     * 生成一个随机的数组
     * @param length    数组的长度
     * @param max       数组中最大的数字
     */
    public static Integer[] generateRandomArray(int length,int max){
        Integer [] array = new Integer[length];
        for (int i = 0 ; i < length ; i ++){
            Random random = new Random();
            int value = random.nextInt(max);
            array[i] = value;
        }
        return array;
    }

    /**
     * 生成一个几乎有序的的数组
     * @param length    数组的长度
     * @param notOrderPair       有多少对无序的数据
     */
    public static Integer[] generateOrderArray(int length,int notOrderPair){
        Integer [] array = new Integer[length];
        for (int i = 0 ; i < length ; i ++){
            array[i] = i;
        }

        for (int i = 0 ; i < notOrderPair ; i ++){
            Random random = new Random();
            int one = random.nextInt(length);
            int another = random.nextInt(length);
            if(one == another){
                i--;
            }
            SortUtils.swap(array,one,another);
        }
        return array;
    }


    public static Integer[] split(Integer [] array,int begin ,int end){
        Integer[] a = new Integer[end - begin];
        for (int i = 0; i < end - begin; i++) {
            a[i] = array[begin+i];
        }
        return a;
    }
    /**
     * 格式输出数组
     */
    public static void print (Integer[] array){
        int index = 1;
        for (int value : array) {
            if(index >= 30){
                System.out.println();
                index = 1;
            }
            System.out.print(value);
            System.out.print('\t');
            index ++;
        }
        System.out.println();
    }

    public static <T> void swap(T[] array , int aIndex ,int bIndex){
        T tmp = array[aIndex];
        array[aIndex] = array[bIndex];
        array[bIndex] = tmp;
    }

    public static Integer[] testSort(String name ,Sort sort,Integer [] array){
        long begin = System.currentTimeMillis();
        Integer [] result = sort.sort(array);
        long end = System.currentTimeMillis();
        System.out.println(name + "：" + (end - begin)/1000.0);
        return result;
    }

    static interface Sort{
        Integer[] sort(Integer[] array);
    }


}
